import { accessSync, mkdirSync, writeFileSync } from 'fs'
import { resolve } from 'path'

let id = 0

export const DEMO_DIR = '.vitepress/.cache/demo'

export function component() {
  return {
    name: 'rollup-plugin-component',

    buildStart() {
      try {
        accessSync(DEMO_DIR)
      } catch (error) {
        mkdirSync(DEMO_DIR)
      }
    },

    transform: {
      order: 'pre' as 'pre' | 'post' | null | undefined,
      handler(src: string, id: string) {
        if (/\.(md)/.test(id)) {
          return { code: createFile(src), map: null }
        }
      }
    }
  }
}

function createFile(src: string) {
  const append: string[] = []
  let codeBlock, ext, code
  src = src.replace(/(:::\s*demo)([\s\S]*?)(:::)/g, (match, $1, $2, $3) => {
    codeBlock = $2
    ;[, ext, code] = /```(\w+)([\s\S]*?)```/.exec(codeBlock.trim()) || []
    const name = `MemoBlock${id++}`
    try {
      writeFileSync(resolve(DEMO_DIR, `${name}.${ext}`), code.trim())
      append.push(`import ${name} from '@demo/${name}.${ext}'`)
    } catch (error) {
      console.log(error)
    }
    return $1 + ' ' + name + $2 + $3
  })
  if (append.length) {
    append.unshift('<script setup>')
    append.push('</script>')
  }
  return src + '\r\n' + append.join('\r\n')
}
